package com.untrance.shop.core.service.bean;

import java.util.ArrayList;
import java.util.List;

import com.untrance.shop.common.filters.model.ProductsCatalogFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Key;
import com.untrance.shop.common.utils.PagerUtils;
import com.untrance.shop.common.vo.ProductDetailsVO;
import com.untrance.shop.core.builder.vo.ProductDetailsVOBuilder;
import com.untrance.shop.core.dao.ProductDao;
import com.untrance.shop.core.service.CategoryService;
import com.untrance.shop.core.service.ImageService;
import com.untrance.shop.core.service.ProductService;
import com.untrance.shop.model.Product;

/**
 * @author eugene zadyra
 */
@Service("productService")
public class ProductServiceBean implements ProductService {
	@Autowired
	private ProductDao productDao;

	@Autowired
	private CategoryService categoryService;

	@Autowired
	ImageService imageService;

	@Override
	public Product addProduct(Product product) {
		return productDao.add(product);
	}

	@Override
	public List<Product> getAllProducts() {
		return new ArrayList<Product>(productDao.findAll());
	}

	@Override
	public Integer getProductsCount() {
		return productDao.countAll();
	}

	@Override
	public List<Product> getLimitedAmountOfProducts(Key categoryKey, Integer page, Integer itemsPerPage) {
		ProductsCatalogFilter filter = PagerUtils.updateFilterPaginationInfo(new ProductsCatalogFilter(), page, itemsPerPage);
		if (categoryKey != null) {
			filter.setCategoryIdList(categoryService.getSubcategoryKeys(categoryKey));
		}
		return productDao.findEntitiesByFilter(filter);
	}

	@Override
	public Integer getProductsCountInCategory(Key categoryKey) {
		ProductsCatalogFilter filter = new ProductsCatalogFilter();
		if (categoryKey != null) {
			filter.setCategoryIdList(categoryService.getSubcategoryKeys(categoryKey));
		}
		return productDao.findEntitiesCountByFilter(filter);
	}

	@Override
	public Product get(Key key) {
		return productDao.find(key);
	}

	@Override
	public ProductDetailsVO getProductDetailsVO(Key productKey) {
		Product product = get(productKey);
		return new ProductDetailsVOBuilder().createVO(product);
	}

}
